package org.mozhu.mboot.core.web.interceptor;

import org.mozhu.mboot.core.web.Constants;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置通用数据的Interceptor <br/>
 * 1、ctx---->request.contextPath<br/>
 * 2、currentURL---->当前地址<br/>
 * 3、BackURL---->上一个页面地址<br/>
 */
public class CommonDataInterceptor extends BaseHandlerInterceptorAdapter {

	private static final String[] DEFAULT_EXCLUDE_PARAMETER_PATTERN = new String[] { "\\&\\w*page.pn=\\d+", "\\?\\w*page.pn=\\d+", "\\&\\w*page.size=\\d+" };

	private String[] excludeParameterPatterns = DEFAULT_EXCLUDE_PARAMETER_PATTERN;

	public void setExcludeParameterPatterns(String[] excludeParameterPatterns) {
		this.excludeParameterPatterns = excludeParameterPatterns;
	}

	@Override
	public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (request.getAttribute(Constants.CONTEXT_PATH) == null) {
			request.setAttribute(Constants.CONTEXT_PATH, request.getContextPath());
		}
		if (request.getAttribute(Constants.CURRENT_URL) == null) {
			request.setAttribute(Constants.CURRENT_URL, extractCurrentURL(request, true));
		}
		if (request.getAttribute(Constants.NO_QUERYSTRING_CURRENT_URL) == null) {
			request.setAttribute(Constants.NO_QUERYSTRING_CURRENT_URL, extractCurrentURL(request, false));
		}
		if (request.getAttribute(Constants.BACK_URL) == null) {
			request.setAttribute(Constants.BACK_URL, extractBackURL(request));
		}
		return true;
	}

	private String extractCurrentURL(HttpServletRequest request, boolean needQueryString) {
		String url = request.getRequestURI();
		String queryString = request.getQueryString();
		if (!StringUtils.isEmpty(queryString)) {
			queryString = "?" + queryString;
			for (String pattern : excludeParameterPatterns) {
				queryString = queryString.replaceAll(pattern, "");
			}
			if (queryString.startsWith("&")) {
				queryString = "?" + queryString.substring(1);
			}
		}
		if (!StringUtils.isEmpty(queryString) && needQueryString) {
			url = url + queryString;
		}
		return getBasePath(request) + url;
	}

	/**
	 * 上一次请求的地址<br/>
	 * 1、先从request.parameter中查找BackURL <br/>
	 * 2、获取header中的 referer<br/>
	 */
	private String extractBackURL(HttpServletRequest request) {
		String url = request.getParameter(Constants.BACK_URL);
		if (StringUtils.isEmpty(url)) {
			url = request.getHeader("Referer");
		}
		if (!StringUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
			return url;
		}
		if (!StringUtils.isEmpty(url) && url.startsWith(request.getContextPath())) {
			url = getBasePath(request) + url;
		}
		return url;
	}

	private String getBasePath(HttpServletRequest req) {
		StringBuffer baseUrl = new StringBuffer();
		String scheme = req.getScheme();
		int port = req.getServerPort();
		baseUrl.append(scheme); // http, https
		baseUrl.append("://");
		baseUrl.append(req.getServerName());
		if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
			baseUrl.append(':');
			baseUrl.append(req.getServerPort());
		}
		return baseUrl.toString();
	}

}
